﻿using AutoMapper;
using MediatR;
using SqlSugar;
using Warehouse.Domain;
using Warehouse.ErrorCord;
using Warehouse.Read.Api.Actions.Command.WarehouseCategory;
using Warehouse.Read.Api.DTO;

namespace Warehouse.Read.Api.Actions.CommandHandel.WarehouseCategory
{
    public class GetTreeCommandHandle : IRequestHandler<GetTreeCommand, APIResult<List<TreeDTO>>>
    {
        private readonly ISqlSugarClient db;
        private readonly IMapper mapper;

        public GetTreeCommandHandle(ISqlSugarClient db, IMapper mapper)
        {
            this.db = db;
            this.mapper = mapper;
        }

        public async Task<APIResult<List<TreeDTO>>> Handle(GetTreeCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<TreeDTO>> result=new APIResult<List<TreeDTO>>();
            result.Code = APIEnum.Success;
            result.Msg = "查询树形结构";
            result.Data =CetTree(0);
            return await Task.FromResult(result);
            
        }


        public List<TreeDTO> CetTree(int ParentId)
        {
            var list = db.Queryable<Warehouse.Domain.WarehouseCategory>().Where(x => x.ParentId == ParentId&&x.IsDel==false);
            var listdto = mapper.Map<List<TreeDTO>>(list.ToList());
            foreach (var item in listdto)
            {
                item.Chidren = CetTree(item.WarehouseTypeId);
            }
            return listdto;
        }
    }
}
